<template>
  <base-breadcrumb>
    <searchData :searchData="searchArr" @search="search"></searchData>
    <a-card>
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleUpdate('add')" v-btnPermission="'hse_023_add_01'">新增设备
        </a-button>
      </div>
      <!-- 机械设备列表统计 -->
      <!--      <div class="table-operateors mb20">-->
      <!--        <div class="pub-table-select-count" style="margin: 10px 0">-->
      <!--          <a-icon type="info-circle" theme="twoTone" />-->
      <!--          <span>-->
      <!--                        机械设备数：-->
      <!--                        <a>{{ statistical.num }}</a-->
      <!--                        >个-->
      <!--                    </span>-->
      <!--        </div>-->
      <!--      </div>-->
      <list-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :request="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        showPagination="auto"
      >
        <span slot="sort" slot-scope="text, record, index">{{ index + 1 }}</span>
        <span slot="auditStatus" slot-scope="text, record">
                    <list-status :status="record.auditStatus" conversion="en" :text="text"></list-status>
                </span>
        <template slot="operation" slot-scope="text, record">
          <MoreButton>
            <a @click="handleUpdate('look', record)" v-btnPermission="'hse_023_loo_04'">查看</a>
            <a @click="handleUpdate('edit', record)" v-btnPermission="'hse_023_edi_02'">编辑</a>
            <a
              @click="openModal(record);visible = true"
              v-btnPermission="'hse_023_add_05'"
            >维保</a>
            <a @click="handleUpdate('del', record)"
                  v-btnPermission="'hse_023_del_03_cp'"
            >删除</a>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
    <a-modal
      title="添加设备维修日志"
      :width="900"
      :visible="visible"
      class="add-maintenance"
      @cancel="
                visible = false
                form.fileInfoList = []
            "
      :confirm-loading="loading"
      @ok="addMaintenance"
    >
      <a-form-model
        ref="ruleForm"
        :model="modalData"
        :rules="rules"
        :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-model-item label="所属分公司：" class="branchComName">
              <span>{{modalData.branchComName}}/{{modalData.projectName}}</span>
              <!-- <BaseInput disabled placeholder="请选择" v-model="modalData.branchComName"></BaseInput> -->
            </a-form-model-item>
          </a-col>

          <!-- <a-col :md="12" :sm="12">
            <a-form-model-item label="所属项目：">
              <BaseInput disabled v-model="modalData.projectName"></BaseInput>
            </a-form-model-item>
          </a-col> -->
          <a-col :md="12" :sm="12">
            <a-form-model-item label="设备">
              <BaseInput disabled v-model="modalData.equipType"></BaseInput>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="维保类型" prop="maintenanceTypeId">
              <a-select placeholder="请选择" v-model="modalData.maintenanceTypeId">
                <a-select-option v-for="i in maintenanceType" :key="i.id" :value="i.id">
                  {{ i.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="维修/保养人" prop="employeeName">
              <BaseInput v-model="modalData.employeeName"></BaseInput>
              <!-- <a-select placeholder="请选择" v-model="modalData.employeeId">
                <a-spin v-if="fetchingOrganizePeopleList" slot="notFoundContent" size="small" />
                <a-select-option
                  v-for="i in organizePeopleList"
                  :key="i.employeeId"
                  :value="i.employeeId"
                >{{ i.employeeName }}
                </a-select-option>
              </a-select> -->
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <a-form-model-item label="维保时间" prop="maintenanceDate">
              <a-date-picker placeholder="请输入" v-model="modalData.maintenanceDate"></a-date-picker>
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-model-item label="维保内容" prop="content">
              <BaseTextarea placeholder="请选择" v-model="modalData.content"></BaseTextarea>
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-model-item label="照片上传">
              <BUploadVModel
                uploadType="image-list"
                v-model="modalData.fileInfoList"
                businessCode="SHE05"
              ></BUploadVModel>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </base-breadcrumb>
</template>
<script>
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import OrgTreeSelect from '@/components/OrgTreeSelect'
import { STable } from '@/components'
import { addMaintenance, deleteEquipment, getEquipmentManagemenList } from '@/api/safetySupervision/equipmentManagement'
import { getSelectListByType } from '@/api/safetySupervision/common.js'
import { getOrganizePeopleList } from '@/api/safetySupervision/emergencyDrill'
import BUploadVModel from '@/components/BComponents/BUploadVModel'

const searchArr = [
  {
    name: '所属单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
  },
  // {
  //   name: '所属分公司',
  //   valueKey: 'branchComId',
  //   type: SelectSubCompany
  // },
  // {
  //   name: '所属项目',
  //   keyValue: 'branchComId',
  //   valueKey: 'projectId',
  //   type: SelectProject
  // },
  {
    name: '设备类型',
    value: 'equipTypeId',
    type: 'select',
    data: []
  },
  {
    name: '设备分类',
    value: 'equipTypeCode',
    type: 'select',
    data: [
      { label: '一类', value: '0' },
      { label: '二类', value: '1' },
      { label: '三类', value: '2' }
    ]
  },
  {
    name: '设备型号',
    value: 'specModel',
    type: 'input'
  },
  {
    name: '状态',
    value: 'equipStatusId',
    type: 'select',
    data: []
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    STable,
    SelectSubCompany,
    SelectProject,
    BUploadVModel
  },
  data() {
    return {
      columns: [
        { title: '序号', dataIndex: 'sort', scopedSlots: { customRender: 'sort' } },
        { title: '设备编号', dataIndex: 'equipCode' },
        { title: '设备类型', dataIndex: 'equipType' },
        { title: '设备分类', dataIndex: 'equipTypeName' },
        { title: '规格型号', dataIndex: 'specModel' },
        { title: '租赁单位', dataIndex: 'propertyUnit' },
        { title: '进场日期', dataIndex: 'entryTime' },
        { title: '责任人', dataIndex: 'respEmployeeName' },
        { title: '所属分公司', dataIndex: 'branchComName', width: 150 },
        { title: '所属项目', dataIndex: 'projectName' },
        { title: '使用状态', dataIndex: 'equipStatus' },
        // {
        //   title: '状态',
        //   dataIndex: 'auditStatus',
        //   scopedSlots: { customRender: 'auditStatus' }
        // },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 220,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      visible: false,
      searchArr,
      loading: false,
      form: {},
      modalData: {},
      statistical: { num: '' },
      rules: {
        maintenanceTypeId: [{ required: true, message: '请选择维保类型' }],
        employeeName: [{ required: true, message: '请输入维保人' }],
        maintenanceDate: [{ required: true, message: '请选择维保时间' }],
        content: [{ required: true, message: '请输入维保内容' }]
      },
      fetchingOrganizePeopleList: false,
      maintenanceType: [],
      organizePeopleList: [],
      queryParam: {},
      loadData: async (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        const [err, res] = await getEquipmentManagemenList(requestParameters)
        return new Promise((resolve, reject) => {
          if (err) {
            reject(err)
          } else {
            this.statistical.num = res.totalSize
            resolve(res)
          }
        })
      }
    }
  },
  created() {
    this.getSelectList('31') //设备状态
    this.getSelectList('13') //设备分类
  },
  methods: {
    fileArrysData(val) {
      this.modalData.fileInfoList = val
    },
    openModal(data) {
      this.modalData = {}
      this.modalData.branchComName = data.branchComName
      this.modalData.projectName = data.projectName
      this.modalData.equipType = data.equipType
      this.modalData.equipmentId = data.id
      this.getSelectList('16')
      // 2022-01-19 维修保养人改为输入，不再查询人员
      // this.getOrganizePeopleList(data.projectId)
    },
    //获取项目下的人员列表
    getOrganizePeopleList(id) {
      let params = {
        id: id
      }
      this.fetchingOrganizePeopleList = true
      getOrganizePeopleList(params).then((res) => {
        let obj = {}
        res.data = res.data.reduce((cur, next) => {
          obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
          return cur
        }, []) //设置cur默认类型为数组，并且初始值为空的数组
        console.log(res.data)
        this.fetchingOrganizePeopleList = false
        this.organizePeopleList = res.data || []
      })

      console.log(this.organizePeopleList)
    },
    async addMaintenance() {
      if (!this.validateForm()) return
      this.loading = true
      this.modalData.auditStatus = 'SUBMITTED'
      console.log(this.modalData)
      // if (this.modalData.maintenanceDate._isAMomentObject) {
      //     this.modalData.maintenanceDate = this.modalData.maintenanceDate.format('YYYY-MM-DD HH:mm:ss')
      // }

      console.log(this.modalData)
      const [err, res] = await addMaintenance(this.modalData)
      this.loading = false
      if (!err) {
        this.visible = false
        this.$message.success('成功')
      }
    },
    //获取设备状态
    async getSelectList(type) {
      const [err, res] = await getSelectListByType({ type })
      if (!err) {
        res.data.forEach((item) => {
          item.value = item.id
          item.label = item.name
        })
        if (type == '31') {
          this.searchArr[this.searchArr.length - 1].data = res.data || []
        } else if (type == '13') {
          this.searchArr[1].data = res.data || []
        } else if (type == '16') {
          this.maintenanceType = res.data || []
        }

        // this.searchArr = searchArr
        // console.log(this.searchArr)
      }
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((valid) => {
        flag = valid
        if(!valid) {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    //搜索
    search(val = {}) {
      const year = new Date().getFullYear()
      this.queryParam = {
        ...val,

        beginTime:
          (val.applyTime && val.applyTime.length && val.applyTime[0].format('YYYY-MM-DD HH:mm:ss')) || void 0,
        endTime:
          (val.applyTime && val.applyTime.length && val.applyTime[1].format('YYYY-MM-DD HH:mm:ss')) || void 0
      }

      this.$refs.table.refresh(true)
    },
    async deleteEquipment(data) {
      const [err, res] = await deleteEquipment({ id: data.id })
      if (!err) {
        this.$message.success('成功')
        this.$refs.table.refresh(true)
      }
    },
    // 处理更新操作（新增、编辑）
    async handleUpdate(type, data = {}) {
      if (type == 'del') {
        let that = this
        this.$confirm({
          title: '温馨提示',
          content: '确定是否删除数据？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            return that.deleteEquipment(data)
          }
        })
      } else {
        this.$router.push({
          name: 'addEquipmentManagement',
          query: {
            id: data.id || '',
            pageType: type
          }
        })
      }
    }
  }
}
</script>
<style scoped lang="less">
@deep: ~'>>>';
 .add-maintenance{
   @{deep} .branchComName{
    .ant-form-item-control{
        background-color: #f5f5f5;
        cursor: not-allowed;
        line-height: 28px;
        border: 1px solid #d9d9d9;
        padding-left: 10px;
    }
   }
 }
</style>
